#coding=utf-8
from utility import *

def add_host(link):
    host = 'http://www.technica.com.cy/'
    return host+link
    
def get_links(soup):
    links = []
    uls = soup.findAll('ul') 
    uls = [ul for ul in uls if ul['class']=='sub']
    
    for ul in uls:
        lis = ul.findAll('li')
        for li in lis:
            links.append([unescape(li.a.string), add_host(li.a['href'].split('?')[0])])    
    return links

def get_items(soup):
    items = []
    
    divs = []
    for div in soup.findAll('div'):
        try:
            n = div['class']
        except:
            continue
        else:
            if n == 'description':
                divs.append(div)
            
    for div in divs:
        ss = div.findAll('strong')
        link = add_host(ss[0].parent['href'])
        
        try:
            price = ss[-1].string.split(';')[1].strip()
        except:
            price = 0
            
        item = [ss[0].string, price, link]
        
        items.append(item)
    return items    

def get_next_link(soup):
    for a in soup.findAll('a'):
        if a.string and a.string.startswith('Next'):
            return add_host(a['href'])
    return None

def get_a_category(link):
    items = []
    
    while link:
        soup = get_soup(link)
        items.extend( get_items(soup) )
        link = get_next_link(soup)
        
    return items
        
def get_description(soup):
    d = soup.findAll('div', {'class':'overview'})[0]
    return get_text(d)

def get_spec(soup):
    specs = []
    tb = soup.findAll('div', {'class':'technical'})[0].table
    trs = tb.findAll('tr')
    for tr in trs:
        tds = tr.findAll('td')
        r = []
        for td in tds:
            s = get_string(td)
            if not s:r.append('')
            else:
                if s.upper()!= s:
                    s = s.replace('\t',  ' ')
                    r.append(s)
        specs.append(r)
    specs = [sp for sp in specs if len(sp) == 2 and (sp[0] or sp[1]) ]
    return specs
                 
            

